﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WuxiWTO.Mapping;
using WutiWTO.Common;
using System.Data.Linq;

namespace WuxiWTO.Web.backend
{
    public partial class categoryList : BasePage
    {
        WTODataContext contex = new WTODataContext();
        PagedDataSource psd = new PagedDataSource();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid();
            }
        }
        private void BindGrid()
        {
            AspNetPager1.RecordCount = contex.categories.Count();

            psd.DataSource = (from c in contex.categories orderby c.sort_num ascending select c).ToList();
            psd.AllowPaging = true;
            psd.CurrentPageIndex = AspNetPager1.CurrentPageIndex - 1;
            psd.PageSize = AspNetPager1.PageSize;

            this.rptCategory.DataSource = psd;
            this.rptCategory.DataBind();
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindGrid();
        }

        protected void rptCategory_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var item = e.Item.DataItem;
                category cat = item as category;
                CheckBox chkNav = e.Item.FindControl("chkNav") as CheckBox;
                Label recordNo = e.Item.FindControl("lblNo") as Label;
                LinkButton button = e.Item.FindControl("btnDelete") as LinkButton;
                int pid = cat.art_parent_kind.Value;
                chkNav.Checked = cat.visiable.HasValue ? cat.visiable.Value : false;
                recordNo.Text = (e.Item.ItemIndex + 1 + (AspNetPager1.PageSize * (AspNetPager1.CurrentPageIndex-1))).ToString();
                button.Attributes.Add("onclick", "return confirm('您确定要删除吗？删除后该分类下面的所有文章也将被删除');");
            }

        }

        protected void rptCategory_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "DeleteCate")
            {
                int category_id = Convert.ToInt32(e.CommandArgument);
                category cat = contex.categories.SingleOrDefault(p => p.art_kind_id == category_id);
                if (cat != null)
                {
                    contex.categories.DeleteOnSubmit(cat);
                    var arts = contex.articles.Where(p => p.parent_category_id == category_id || p.category_id == category_id);
                    contex.articles.DeleteAllOnSubmit(arts);
                    contex.SubmitChanges();
                }
                BindGrid();
            }
        }
    }
}